package com.linxi.wordslog.wordslogviewmodel

import android.content.Context
import androidx.core.content.edit
import androidx.lifecycle.*
import com.linxi.wordslog.WordApplication
import com.linxi.wordslog.data.room.Word
import com.linxi.wordslog.repositories.WordRepository
import kotlinx.coroutines.launch

const val VIEW_TYPE = "view_type"
const val IS_USING_CARD_VIEW = "is_using_card_view"
const val USER_INFO = "user_info"
const val USER_NAME = "user_name"
const val USER_AGE = "user_age"
const val USER_SEX = "user_sex"
const val USER_SIGN = "user_sign"
class WordViewModel(private val wordRepository: WordRepository): ViewModel() {


    private val shp = WordApplication.context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE)
    private val _name= MutableLiveData<String>(shp.getString(USER_NAME, "林夕"))
    private val _sex = MutableLiveData<Int>(shp.getInt(USER_SEX, 1))
    private val _age = MutableLiveData<Int>(shp.getInt(USER_AGE, 18))
    private val _sign = MutableLiveData<String>(shp.getString(USER_SIGN, "逢考必过!!"))

    val name: LiveData<String> = _name
    val age: LiveData<Int> = _age
    val sex: LiveData<Int> = _sex
    val sign: LiveData<String?> = _sign

    fun saveInfo(name: String, age: Int, sex: Int, sign: String) {
        _name.value = name
        _age.value = age
        _sex.value = sex
        _sign.value = sign
        shp.edit {
            putString(USER_NAME, name)
            putInt(USER_AGE, age)
            putInt(USER_SEX, sex)
            putString(USER_SIGN, sign)
        }
    }

    fun getAllWords() =
        wordRepository.getAllWords()
    fun findWordsWithPattern(pattern: String): LiveData<List<Word>> =
        wordRepository.findWordsWithPattern(pattern)

    fun insertWords(vararg word: Word) {
        viewModelScope.launch {
            wordRepository.insertWords(*word)
        }
    }

    fun deleteAllWords() {
        viewModelScope.launch {
            wordRepository.deleteAllWords()
        }
    }

    fun updateWords(vararg words: Word) {
        viewModelScope.launch {
            wordRepository.updateWords(*words)
        }
    }

    fun deleteWords(vararg words: Word) {
        viewModelScope.launch { wordRepository.deleteWords(*words) }
    }
}